import pymysql

class DBTolls(object):
    # 创建连接--类方法，可以直接使用类名调用
    @classmethod
    # 设置私有方法
    def __create_conn(cls):
        conn = pymysql.connect(host="localhost", port=3306, user="root",
                               password="root", database="ihrm", charset="utf8")
        return conn

    # 查询一条语句
    @classmethod
    def query_one(self, sql):
        conn = None
        cursor = None
        try:
            # 创建连接， 借助类名，调用类方法 creat_conn
            conn = DBTolls.__create_conn()
            # 创建游标
            cursor = conn.cursor()
            # 执行语句， 做查询
            cursor.execute(sql)
            # 提取一条记录
            res = cursor.fetchone()
        except Exception as err:
            print("查询失败：", str(err))
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            conn.close()
            return res


    @ classmethod
    # 增删改
    def db_uid(cls, sql):
        conn = None
        cursor = None
        try:
            conn = DBTolls.__create_conn()
            cursor = conn.cursor()
            cursor.execute(sql)
            print("Affect rows:", conn.affected_rows())
            # 提交事务
            conn.commit()
        except Exception as err:
            print("操作失败:", str(err))
            # 回滚事务
            conn.rollback()

        finally:
            cursor.close()
            conn.close()


if __name__ == "__main__":
    print(DBTolls.db_uid("delete from bs_user where mobile = '17331202748';"))

